package com.wangzefeng.shop.filter;

import com.alibaba.fastjson.JSONObject;
import com.wangzefeng.shop.constant.CommonConstants;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Auther: wangzefeng
 * @Date: 2021/3/17 10:16
 * @Description:
 */
@Slf4j
public class PasswordFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public PasswordFilter(AuthenticationManager authenticationManager){
        this.authenticationManager=authenticationManager;
    }

    //身份认证(接收并解析用户凭证)
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username,password,new ArrayList<>()));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        String token="";
        Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
        List<String> roles=new ArrayList<>();
        for (GrantedAuthority g:authorities){
            roles.add(g.getAuthority());
        }
        Calendar instance = Calendar.getInstance();
        Date startTime = instance.getTime();
        instance.add(Calendar.MINUTE,30);
        Date endTime = instance.getTime();
        token = Jwts.builder()
                .setSubject(authResult.getName() + "-" + roles)
                .setIssuedAt(startTime)//签发时间
                .setExpiration(endTime)//过期时间
                .signWith(SignatureAlgorithm.HS512, CommonConstants.SIGNING_KEY) //采用什么算法是可以自己选择的，不一定非要采用HS512
                .compact();
        // 登录成功后，返回token到header里面
        response.addHeader("Authorization", "Bearer " + token);
        JSONObject result = new JSONObject();
        result.put("status",200);
        result.put("data","Bearer " + token);
        response.getWriter().write(result.toJSONString());
    }
}
